package com.myhome.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.config.constant.R;
import com.myhome.domain.*;
import com.myhome.dto.UserDto;
import com.myhome.model.*;
import com.myhome.service.UserAuthAuditRecordService;
import com.myhome.service.UserAuthInfoService;
import com.myhome.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author QYiXin
 * @Date 2021 10 13 10 42
 **/
@RestController
@Api(tags = "user控制器")
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserAuthInfoService userAuthInfoService;
    @Autowired
    UserAuthAuditRecordService userAuthAuditRecordService;

    @GetMapping
    @ApiOperation("获取用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数"),
            @ApiImplicitParam(name = "mobile", value = "会员的手机号"),
            @ApiImplicitParam(name = "userId", value = "会员的Id,精确查询"),
            @ApiImplicitParam(name = "userName", value = "会员的名称"),
            @ApiImplicitParam(name = "realName", value = "会员的真实名称"),
            @ApiImplicitParam(name = "status", value = "会员的状态")

    })
    public R<Page<User>> getPagesUsers(@ApiIgnore Page<User> page, String mobile, Long userId,
                                       String userName, String realName, Byte status) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<User> result = userService.getPagesUsers(page, mobile, userId, userName, realName, status);
        return R.ok(result);
    }

    @PostMapping("/status")
    @ApiOperation("修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "会员的id"),
            @ApiImplicitParam(name = "status", value = "会员的状态"),
    })
    public R updateUserStatus(Long id, Byte status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        boolean isUpdate = userService.updateById(user);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("修改失败");
    }

    @PatchMapping
    @ApiOperation(value = "修改用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "会员的json数据"),
    })
    public R updateUser(@RequestBody User user) {
        boolean isUpdate = userService.updateById(user);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("修改失败");
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取用户的详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的Id")
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<User> getUserInfo(Long id) {
        return R.ok(userService.getById(id));
    }

    @GetMapping("/directInvites")
    @ApiOperation(value = "查询该用户邀请的用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "该用户的Id"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数"),

    })
    public R<Page<User>> getInvitedPerson(@ApiIgnore Page<User> page, Long userId) {
        Page<User> result = userService.getInvitedPerson(page, userId);
        return R.ok(result);
    }

    @GetMapping("/auths")
    @ApiOperation(value = "查询用户的审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数"),
            @ApiImplicitParam(name = "mobile", value = "会员的手机号"),
            @ApiImplicitParam(name = "userId", value = "会员的Id,精确查询"),
            @ApiImplicitParam(name = "userName", value = "会员的名称"),
            @ApiImplicitParam(name = "realName", value = "会员的真实名称"),
            @ApiImplicitParam(name = "reviewsStatus", value = "会员的状态")

    })
    public R<Page<User>> getPagesUserAuth(@ApiIgnore Page<User> page, String mobile,
                                          Long userId, String userName,
                                          String realName, Byte reviewsStatus) {
        Page<User> result = userService.getPagesAuth(page, mobile, userId, userName, realName, reviewsStatus);
        return R.ok(result);
    }

    @GetMapping("/auth/info")
    @ApiOperation(value = "查询用户的认证详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的Id")
    })
    public R<UseAuthInfoVo> getUserAuthInfo(Long id) {
        User user = userService.getById(id);
        List<UserAuthInfo> userAuthInfoList = null;
        List<UserAuthAuditRecord> authAuditRecordList = null;
        if (user != null) {
            Integer reviewsStatus = user.getReviewsStatus();
            if (reviewsStatus == null || reviewsStatus == 0) {
                authAuditRecordList = Collections.emptyList();
                userAuthInfoList = userAuthInfoService.getAuthInfoByUserId(id);
            } else {
                authAuditRecordList = userAuthAuditRecordService.getAuthRecordByUserId(id);
                if (authAuditRecordList != null) {
                    UserAuthAuditRecord userAuthAuditRecord = authAuditRecordList.get(0);
                    Long authCode = userAuthAuditRecord.getAuthCode();
                    userAuthInfoList = userAuthInfoService.getAuthInfoByAuthCode(authCode);
                }
            }
        }
        return R.ok(new UseAuthInfoVo(user, authAuditRecordList, userAuthInfoList));
    }

    @PostMapping("/auths/status")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的ID"),
            @ApiImplicitParam(name = "authStatus", value = "用户的审核状态"),
            @ApiImplicitParam(name = "authCode", value = "一组图片的唯一标识"),
            @ApiImplicitParam(name = "remark", value = "审核拒绝的原因"),
    })
    public R updateAuthStatus(Long id, Byte authStatus, Long authCode, String remark) {
        boolean isUpdate = userService.updateAuthStatus(id, authStatus, authCode, remark);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail();
    }

    @GetMapping("/current/info")
    @ApiOperation(value = "获取当前登录用户的详情")
    public R<User> getCurrentUserInfo() {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        User result = userService.getById(Long.valueOf(userId));
        result.setPassword("*******");
        result.setPaypassword("*******");
        return R.ok(result);
    }

    @PostMapping("/authAccount")
    @ApiOperation(value = "用户的实名认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAuthForm", value = "用户认证信息")
    })
    public R checAuthInfo(@RequestBody UserAuthForm userAuthForm) {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        Boolean isCheckAuth = userService.checkAuth(Long.valueOf(userId), userAuthForm);
        if (isCheckAuth) {
            return R.ok();
        }
        return R.fail("认证失败");
    }

    @PostMapping("/updatePhone")
    @ApiOperation(value = "修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "newPhoneAndOldPhone", value = "updatePhone 的json数据")
    })
    public R updatePhone(NewPhoneAndOldPhone newPhoneAndOldPhone) {
        String strId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        Boolean isUpdate = userService.updatePhone(Long.valueOf(strId), newPhoneAndOldPhone);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("修改失败");
    }

    @GetMapping("/checkTel")
    @ApiOperation(value = "检查新的手机号是否可用,如可用,则给该新手机发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "新的手机号"),
            @ApiImplicitParam(name = "countryCode", value = "手机号的区域")
    })
    public R checkNewPhone(String mobile, String countryCode) {
        Boolean isCheck = userService.checkNewPhone(mobile, countryCode);
        if (isCheck) {
            return R.ok();
        }
        return R.fail("该手机号不能被使用");
    }

    @PostMapping("/updateLoginPassword")
    @ApiOperation("修改登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updatePasswordInfo", value = "修改登录密码信息")
    })
    public R updateUserLoginPassword(@RequestBody UpdatePasswordInfo updatePasswordInfo) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        Boolean isUpdate = userService.updateLoginPassword(userId, updatePasswordInfo);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("修改失败");

    }

    @PostMapping("/updatePayPassword")
    @ApiOperation("修改登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updatePasswordInfo", value = "修改交易密码信息")
    })
    public R updateUserPayPassword(@RequestBody UpdatePasswordInfo updatePasswordInfo) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        Boolean isUpdate = userService.updatePayPassword(userId, updatePasswordInfo);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("修改失败");

    }

    @PostMapping("/setPayPassword")
    @ApiOperation("重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unsetPasswordInfo", value = "交易密码信息")
    })
    public R unsetPayPassword(@RequestBody UnsetPasswordInfo unsetPasswordInfo) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        Boolean isUpdate = userService.unsetPassword(userId, unsetPasswordInfo);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("充值失败");
    }

    @GetMapping("/invites")
    @ApiOperation("获取邀请人")
    public R<List<User>> getInvitedPerson() {
        List<User> result = userService.getInvitedPeron();
        return R.ok(result);
    }

    @GetMapping("/basic/user")
    @ApiOperation("获取用户部分信息")
    List<UserDto> getBasicUsers(@RequestParam("ids") List<Long> ids) {
        return userService.getManyUsers(ids);
    }

    @GetMapping("/basic/users")
    @ApiOperation("获取用户信息")
    Map<Long,UserDto> getBasicMapUserDto(
            @RequestParam(value = "ids", required = false) List<Long> ids, @RequestParam(value = "username"
            , required = false) String userName, @RequestParam(value = "mobile"
            , required = false) String mobile){
        return userService.getBasicMapUserDto(ids, userName, mobile);
    }
    @PostMapping("/register")
    @ApiOperation(value = "用户的注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "registerParam", value = "用户注册参数")
    })
    public R register(@RequestBody RegisterParam registerParam) {

        boolean isRegister = userService.register(registerParam);
        if (isRegister) {
            return R.ok();
        }
        return R.fail("注册失败");
    }

    @PostMapping("/setPassword")
    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "", value = "")
    })
    public R publicSetPassword(@RequestBody PublicSetPasswordParam publicSetPasswordParam) {
        Boolean isSet = userService.publicSetPassword(publicSetPasswordParam);
        if (isSet) {
            return R.ok();
        }
        return R.fail("修改失败");
    }

}
